package com.ebuy.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ebuy.dao.CustomerDAO;
import com.ebuy.model.Customer;

public class AuthenticatorServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		if (username.equals("admin") && password.equals("pass")) {
			request.getSession().setAttribute("admin", "true");
			request.getSession().setAttribute("loggedIn", "true");
			
			redirect(response, "/Product", false);
		} else if (validateUser(username, password)) {
			CustomerDAO dao = new CustomerDAO();

			Customer customer = dao.getSingleCustomer(username, password);

			request.getSession().setAttribute("admin", "false");
			request.getSession().setAttribute("customer", customer);
			request.getSession().setAttribute("loggedIn", "true");

			redirect(response, "/Product", false);
		} else {
			request.setAttribute("showError", true);

			forward(request, response, "");
		}
	}

	private boolean validateUser(String username, String password) {
		CustomerDAO dao = new CustomerDAO();
		return dao.validateCustomer(username, password);
	}
}
